// pages/shoppingCart.js
import {
  debounce,
  throttle
} from "../../utils/util"

import {
  //获取购物车
  getCart,
  // 更新数量
  updateCart,
  //获取可用优惠卷
  getCartCoupon,
  //确认兑换
  submitCart,
  // 删除商品
  delCart
} from '../../api/index'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 全选
    checkedAll: false,
    // 商品数据
    comArr: [],
    // 下拉刷新
    refBob: false,
    // 合计
    total: 0,
    // 选择数组
    checkArr: [],
    // 优惠卷选择弹窗
    show: false,
    // 优惠卷
    couponArr: [],
    //选择优惠卷id
    couponId: ''
  },
  onShow() {
    this.getCartPage()
  },
  // 获取购物车
  getCartPage: debounce(async function () {
    try {
      const dataObj = await getCart()
      console.log("购物车", dataObj);
      if (dataObj.code == 200) {
        const arr = this.data.checkArr
        if (arr.length != 0) {
          dataObj.data.forEach(item => {
            let obj = arr.find(items => items.id == item.id)
            if (obj) {
              item.checked = obj.checked
            }
          })
        }

        this.setData({
          comArr: dataObj.data
        })
        this.setData({
          checkedAll:dataObj.data.length==0? false:dataObj.data.every(item => item.checked)
        })
      }
      // 统计
      this.totalCount()
    } catch (error) {
      console.log("获取购物车错误：", error);
    }
  }, 500),
  // 下拉刷新
  // 下拉开始
  refStart: debounce(function () {
    console.log("下拉");
    setTimeout(() => {
      this.setData({
        refBob: false
      })
    }, 2000)
  }, 500),
  // 下拉完成
  refSuccess() {
    this.getCartPage()
    console.log("触发1");
  },
  // 商品数量改变
  onChangeNum: debounce(async function (e) {
    const id = e.currentTarget.dataset.id
    console.log("商品数量1：", e.detail);
    console.log("id:", id);
    try {
      const dataObj = await updateCart({
        id,
        goods_count: e.detail
      })

      console.log("更新购物车：", dataObj);
      this.getCartPage()
    } catch (error) {
      console.log("更新购物车错误·：", error);
    }

  }, 500),
  // 全选触发
  onCheckAll(e) {
    console.log("选择：", e.detail);
    let arr = JSON.parse(JSON.stringify(this.data.comArr))
    arr.forEach(item => {
      item.checked = e.detail
    })

    this.setData({
      comArr: arr,
      checkedAll: e.detail,
      checkArr: arr
    })

    // 统计
    this.totalCount()
  },
  // 单选触发
  onCheck(e) {
    const index = e.currentTarget.dataset.index
    console.log("商品选择1：", e.detail);
    console.log("下标1：", index);
    let arr = JSON.parse(JSON.stringify(this.data.comArr))
    arr[index].checked = e.detail
    this.setData({
      comArr: arr,
      checkArr: arr
    })
    console.log("商品数据", this.data.comArr);

    this.setData({
      checkedAll: this.data.comArr.every(item => item.checked)
    })
    // 统计
    this.totalCount()

  },

  // 合计
  totalCount() {
    const arr = this.data.comArr
    let totals = 0
    arr.forEach((item, index) => {
      if (item.checked) {
        totals += item.goods_price * item.goods_count
      }
      return totals
    })
    console.log("合计", totals);
    this.setData({
      total: totals
    })
  },

  // 结算
  async settlement() {
    console.log(this.data.total);
    if (this.data.total != 0) {
      try {
        const amount = this.data.total
        const dataObj = await getCartCoupon({
          amount,
          status: 1
        })
        console.log("获取优惠卷", dataObj);
        if (dataObj.code == 200) {
          this.setData({
            couponArr: dataObj.data,
            show: true
          })
          console.log("选择");
        }

      } catch (error) {
        console.log("获取优惠卷错误：", error);
      }
    } else {
      console.log("未选择");
    }
  },
  // 关闭弹窗
  onClose() {
    this.setData({
      show: false,
      couponId: ''
    })
  },
  // 选择优惠卷
  changeCoupon(e) {
    console.log(e.currentTarget.dataset.id);
    this.setData({
      couponId: e.currentTarget.dataset.id
    })
  },
  // 确认兑换
  async yesCart() {
    try {
      let cart_id_list = this.data.comArr.map(item => {
        if (item.checked) {
          return item.id
        }
      })
      cart_id_list = cart_id_list.filter(item => item)
      const coupon_id = this.data.couponId
      console.log(cart_id_list, coupon_id);
      const dataObj = await submitCart({
        cart_id_list,
        coupon_id
      })
      console.log("确认兑换：", dataObj);
      this.getCartPage()
      this.onClose()
      this.setData({
        checkedAll: false
      })
      if(dataObj.code==200){
        wx.navigateTo({
          url: '/pages/my/orders/orders',
        })
      }
    } catch (error) {
      console.log("确认兑换失败：", error);
    }
  },
  // 删除商品
  async delCartPage(e) {
    try {
      const id = e.currentTarget.dataset.id
      const dataObj = await delCart({
        id
      })
      console.log("删除商品", dataObj);
      if (dataObj.code == 200) {
        this.getCartPage()
      }
    } catch (error) {
      console.log("删除商品错误", error);
    }
  }

})